package net.qktianxia.component.share.wechat.wrshare;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;

import net.qktianxia.component.share.base.SLogger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.List;

import static android.text.TextUtils.isEmpty;

/**
 * 作者： wr
 * 时间： 2017/4/19 18:27
 * 说明： 目前包含intent 分享，uc/qq浏览器分享，修改微信sdk分享，如果以后有新的办法我会继续更新
 */
public class ShareUtils {


    /**
     * 微信纯文本分享
     * @param activity
     * @param share_word
     */
    public static void sharePureText(Context activity, String share_word) {
        try {
            Intent intentFriend = new Intent();
            ComponentName compFriend = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intentFriend.setComponent(compFriend);
            intentFriend.setAction(Intent.ACTION_SEND);
            intentFriend.setType("image/*");
            intentFriend.putExtra(Intent.EXTRA_TEXT, share_word);
            intentFriend.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            activity.startActivity(intentFriend);
        } catch (Exception e) {
            if (e.toString().contains("android.content.ActivityNotFoundException")) {
                Toast.makeText(activity, "您没有安装微信", Toast.LENGTH_SHORT).show();
            }

            SLogger.get().e(e,"");
        }
    }


    /**
     *
     * 微信纯图片分享
     *
     * @param imgFile
     */
    public static void sharePureImage(Context context, File imgFile) {
        try {
            Uri photoUri = null;
            if (imgFile.exists()) {
                if (Build.VERSION.SDK_INT >= 24) {
                    try {
                        //修复微信在7.0崩溃的问题
                        photoUri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(context.getContentResolver(), imgFile.getPath(), "bigbang.jpg", null));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    photoUri = Uri.fromFile(imgFile);
                }
            }
            Intent intentFriend = new Intent();
            ComponentName compFriend = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intentFriend.setComponent(compFriend);
            intentFriend.setAction(Intent.ACTION_SEND);
            intentFriend.setType("image/*");
            intentFriend.putExtra(Intent.EXTRA_STREAM, photoUri);
            intentFriend.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intentFriend);
        } catch (Exception e) {
            if (e.toString().contains("android.content.ActivityNotFoundException")) {
                Toast.makeText(context, "您没有安装微信", Toast.LENGTH_SHORT).show();
            }
            SLogger.get().e(e,"");
        }

    }

    /**
     * 微信图文分享
     * @param shareWord
     * @param imgFile
     */
    public static void shareTextAndImage(Context context, String shareWord, File imgFile) {
        try {
            Uri photoUri = null;
            if (imgFile.exists()) {
                if (Build.VERSION.SDK_INT >= 24) {
                    try {
                        //修复微信在7.0崩溃的问题
                        photoUri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(context.getContentResolver(), imgFile.getPath(), "bigbang.jpg", null));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    photoUri = Uri.fromFile(imgFile);
                }
            }
            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("Kdescription", shareWord);
            intent.putExtra(Intent.EXTRA_STREAM, photoUri);
            context.startActivity(intent);
        } catch (Exception e) {
            if (e.toString().contains("android.content.ActivityNotFoundException")) {
                Toast.makeText(context, "您没有安装微信", Toast.LENGTH_SHORT).show();
            }
            SLogger.get().e(e,"");
        }


    }


//------------------------------------------------------------华丽的分割线------------------------------------------------------------

    /**
     * 通过回调来实现
     *
     * @param AppId        来源id
     * @param packageName  来源包名
     * @param shareTitle   分享标题
     * @param shareContent 分享内容
     * @param shareUrl     分享链接
     * @param type         分享方式 0 好友 1 朋友圈 2 收藏
     * @param shareBitmap  分享图片
     */
    public static void shareWX(WeakReference<Activity> weakReference, String AppId, String packageName, String shareTitle, String shareContent, String shareUrl, int type, Bitmap shareBitmap, GetResultListener onShareLitener) {
        Bitmap localBitmap2 = Bitmap.createScaledBitmap(shareBitmap, 150, 150, true);
        if (shareBitmap != null) {
            shareBitmap.recycle();
            shareBitmap = null;
        }
        //通过原始的微信sdk来组装参数
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = shareUrl;
        WXMediaMessage localWXMediaMessage = new WXMediaMessage(localWXWebpageObject);
        localWXMediaMessage.title = shareTitle;
        localWXMediaMessage.description = shareContent;
        localWXMediaMessage.thumbData = (bmpToByteArray(localBitmap2, true));
        SendMessageToWX.Req localReq = new SendMessageToWX.Req();
        localReq.transaction = System.currentTimeMillis() + "";
        localReq.message = localWXMediaMessage;
        localReq.scene = type;
        //在分享的时候不调用sdk中原有的分享代码，改调用自己的，这里需要注意不要使用新的jar包，里面有的方法已经取消了，就用项目里的
        WxShare.sendReq(weakReference, onShareLitener, localReq, AppId, packageName);
    }

    /**
     * 做分享前的准备，判断当前有哪个应用能进行分享 （使用回调方式）
     *
     * @param weakReference
     * @param shareTitle
     * @param share_word
     * @param shareUrl
     * @param type
     * @param bitmap
     */
    public static void shareWXReady(WeakReference<Activity> weakReference, String shareTitle, String share_word, String shareUrl, int type, Bitmap bitmap, GetResultListener onShareLitener) {
        try {
            if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGEQQ)) {
                SLogger.get().e("安装了QQ");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYQQ, ShareThirdConstant.WEIXINAPPPACKAGEQQ, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener
                );
            } else if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGEUC)) {
                SLogger.get().e("安装了uc");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYUC, ShareThirdConstant.WEIXINAPPPACKAGEUC, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener);
            } else if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGEQQBROWSER)) {
                SLogger.get().e("安装了qqBrowser");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYQQBROWSER, ShareThirdConstant.WEIXINAPPPACKAGEQQBROWSER, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener);
            } else if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGENEWSTODAY)) {
                SLogger.get().e("安装了今日头条");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYNEWSTODAY, ShareThirdConstant.WEIXINAPPPACKAGENEWSTODAY, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener);

            } else if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGEBAIDU)) {
                SLogger.get().e("安装了百度");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYBAIDU, ShareThirdConstant.WEIXINAPPPACKAGEBAIDU, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener);
            } else if (checkApkExist(weakReference.get(), ShareThirdConstant.WEIXINAPPPACKAGESINA)) {
                SLogger.get().e("安装了sina");
                ShareUtils.shareWX(weakReference, ShareThirdConstant.WEIXINAPPKEYSINA, ShareThirdConstant.WEIXINAPPPACKAGESINA, shareTitle
                        , share_word, shareUrl, type, bitmap, onShareLitener);
            } else {
                SLogger.get().e("没有其他的");
//                onShareLitener.onError();
                return;
            }
        } catch (Exception e) {
            SLogger.get().e(Log.getStackTraceString(e));
//            onShareLitener.onError();
        }
    }

    /**
     * 通过rxjava重构分享部分的代码，这里是简写，在真实项目中，可能根据需求的不同要嵌套好几层回调，所以改成rxjava来写
     *
     * @param weakReference
     * @param AppId
     * @param packageName
     * @param shareTitle
     * @param shareContent
     * @param shareUrl
     * @param type
     * @param shareBitmap
     */
    public static void shareWXRX(WeakReference<Activity> weakReference, String AppId, String packageName, String shareTitle, String shareContent, String shareUrl, int type, Bitmap shareBitmap) {
        WeakReference<Bitmap> bmp = new WeakReference(Bitmap.createScaledBitmap(shareBitmap, 150, 150, true));

        //拼接参数还是用原生的sdk来弄
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = shareUrl;
        WXMediaMessage localWXMediaMessage = new WXMediaMessage(localWXWebpageObject);
        localWXMediaMessage.title = shareTitle;
        localWXMediaMessage.description = "";
        localWXMediaMessage.thumbData = (bmpToByteArray(bmp.get(), true));
        SendMessageToWX.Req localReq = new SendMessageToWX.Req();
        localReq.transaction = System.currentTimeMillis() + "";
        localReq.message = localWXMediaMessage;
        localReq.scene = type;
        //在分享的时候不调用sdk中原有的分享代码，改调用自己的，这里需要注意不要使用新的jar包，里面有的方法已经取消了，就用我这项目里的
        WxShare.sendReq(weakReference, localReq, AppId, packageName);
    }

    /**
     * 根据手机上安装的软件返回具体的包名和AppID，这里面其实能做很多处理，我这只是安顺序写下来了，一般qq就返回去了。。。
     *
     * @param context
     * @param shareImage
     * @return
     */
    public static String[] shareWXReadyRx(Context context, String shareImage) {
        String[] strings = new String[3];
        if (checkApkExist(context, ShareThirdConstant.TENTXUNNEWSPAGER)) {
            strings[0] = ShareThirdConstant.TENTXUNNEWSAPPKEY;
            strings[1] = ShareThirdConstant.TENTXUNNEWSPAGER;
            strings[2] = shareImage;
            SLogger.get().e("安装了腾讯新闻");
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.TENTXUNYINGYONGBAOSPAGER)) {
            strings[0] = ShareThirdConstant.TENTXUNYINGYONGBAOSAPPKEY;
            strings[1] = ShareThirdConstant.TENTXUNYINGYONGBAOSPAGER;
            strings[2] = shareImage;
            SLogger.get().e("安装了腾讯应用宝");
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGESINA)) {
            strings[0] = ShareThirdConstant.WEIXINAPPKEYSINA;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGESINA;
            strings[2] = shareImage;
            SLogger.get().e("安装了sina");
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGEQQ)) {
            SLogger.get().e("安装了QQ");
            strings[0] = ShareThirdConstant.WEIXINAPPKEYQQ;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGEQQ;
            strings[2] = shareImage;
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGEUC)) {
            SLogger.get().e("安装了uc");
            strings[0] = ShareThirdConstant.WEIXINAPPKEYUC;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGEUC;
            strings[2] = shareImage;
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGEQQBROWSER)) {
            strings[0] = ShareThirdConstant.WEIXINAPPKEYQQBROWSER;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGEQQBROWSER;
            strings[2] = shareImage;
            SLogger.get().e("安装了qqBrowser");
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGENEWSTODAY)) {
            strings[0] = ShareThirdConstant.WEIXINAPPKEYNEWSTODAY;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGENEWSTODAY;
            strings[2] = shareImage;
            SLogger.get().e("安装了今日头条");
            return strings;

        } else if (checkApkExist(context, ShareThirdConstant.WEIXINAPPPACKAGEBAIDU)) {
            strings[0] = ShareThirdConstant.WEIXINAPPKEYBAIDU;
            strings[1] = ShareThirdConstant.WEIXINAPPPACKAGEBAIDU;
            strings[2] = shareImage;
            SLogger.get().e("安装了百度");
            return strings;
        }
//        } else if (AppUtils.checkApkExists(context, ShareThirdConstant.TENTXUNXIAOMIPAGER)) {
//            strings[0] = ShareThirdConstant.TENTXUNXIAOMIAPPKEY;
//            strings[1] = ShareThirdConstant.TENTXUNXIAOMIPAGER;
//            strings[2] = shareImage;
//            SLogger.get().e("安装了小米浏览器");
//            return strings;
//        }
//        } else if (AppUtils.checkApkExists(context, ShareThirdConstant.WEIXINVIVOPAGER)) {
//            strings[0] = ShareThirdConstant.WEIXINVIVOAPPKEY;
//            strings[1] = ShareThirdConstant.WEIXINVIVOPAGER;
//            strings[2] = shareImage;
//            SLogger.get().e("安装了VIVO浏览器");
//            return strings;
//        }

        return null;
    }

    /**
     * @param shareImage
     * @return
     */
    public static Bitmap getHttpBitmap(String shareImage) {
        URL pictureUrl = null;
        InputStream in = null;
        Bitmap bitmap = null;
        try {
            pictureUrl = new URL(shareImage);
            in = pictureUrl.openStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inSampleSize = 2;
            SoftReference<Bitmap> bitmapSoftReference = new SoftReference<>(BitmapFactory.decodeStream(in, null, options));
            bitmap = bitmapSoftReference.get();
        } catch (Exception e) {
            SLogger.get().e(Log.getStackTraceString(e));
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                SLogger.get().e(Log.getStackTraceString(e));
            }
        }
        return bitmap;
    }


    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        SLogger.get().e("result___长度" + result.length);
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static boolean checkApkExist(Context context, String packageName) {

        if (isEmpty(packageName)) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }


}
